package com.lza.phone.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.lza.phone.entity.OssEntity;
import com.lza.phone.service.AliOssService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.rmi.runtime.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class AliOssServiceImpl implements AliOssService, InitializingBean {
    @Autowired
    private OssEntity ossEntity;
    private  String endpoint;
    private String accessKeyId ;
    private String accessKeySecret ;
    private String bucketName;
    @Override
    public void afterPropertiesSet() throws Exception {
        endpoint=ossEntity.getEndpoint();
        accessKeyId=ossEntity.getAccessKeyId();
        accessKeySecret=ossEntity.getAccessKeySecret();
        bucketName=ossEntity.getBucketName();

    }
    @Override
    public void createBucket() {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建存储空间。
        ossClient.createBucket(bucketName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    @Override
    public String upload(MultipartFile file) {
       /* String objectName = "锋头";
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String content = "Hello OSS";
        ObjectMetadata objectMetadata=new ObjectMetadata();
        objectMetadata.setContentType("image/jpg");
        try {
            ossClient.putObject(bucketName, objectName, file.getInputStream(),objectMetadata);
        } catch (IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return "上传文件成功";*/
       //上传地址
        String uploadUrl=null;
        try {
            //创建实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //判断bucketName是否存在
            if(!ossClient.doesBucketExist(bucketName)){
                //创建bucket
                ossClient.createBucket(bucketName);
                //设置bucket属性
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            //获取上传的文件流
            InputStream inputStream=file.getInputStream();
            //构建日期的文件夹路径 avatar/2021/9/12/文件名
           String datePath= new DateTime().toString("yyy/MM/dd");
           //获取上传文件的全名称
            String original = file.getOriginalFilename();
            //获取uuid 随机生成的,每次都不同 9c649622-7b7b-4fca-ba74-daae5ea4b3c8 变为9c6496227b7b4fcaba74daae5ea4b3c8
            String fileName = UUID.randomUUID().toString().replace("-", "");
            //获取文件路径的扩展名 meizi.jpg  就应该是jpg
            String fileType = original.substring(original.lastIndexOf("."));
            //并接文件名称 9c6496227b7b4fcaba74daae5ea4b3c8.jpg
            String newName=fileName+fileType;
            //生成文件夹   avatar/2021/9/12/9c6496227b7b4fcaba74daae5ea4b3c8.jpg
           fileName= datePath+"/"+newName;
            //每次上传的文字都是不能相同的---uuid方法 文件格式：yyyy/MM/dd+uuid

            //要实现图片预览效果，还需要设置
            //1.设置文件的ACL(权限)，要么是公共读，要么是公共读写
            //2.一定要设置文本类型(image/jpg)
            ObjectMetadata objectMetadata=new ObjectMetadata();
            //设置公共读权限
            objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
            objectMetadata.setContentType(getContentType(fileType));
            ossClient.putObject(bucketName, fileName, file.getInputStream(),objectMetadata);
            // 关闭OSSClient。
            ossClient.shutdown();
            //默认十年不过期
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            //获取在线访问的url bucket名称  文件名   过期时间
            uploadUrl = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString();

        }catch (Exception e){
            e.printStackTrace();
        }
          //返回数据是关键如果你直接返回uploadUrl那么后面就会出现很多参数，所以要进行截取
        return uploadUrl.substring(0,uploadUrl.indexOf("?"));

    }

    @Override
    public void download(String fileName) throws IOException {

    }

    @Override
    public void listFile() {//列举文件
    // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    // ossClient.listObjects返回ObjectListing实例，包含此次listObject请求的返回结果。
        ObjectListing objectListing = ossClient.listObjects(bucketName);
    // objectListing.getObjectSummaries获取所有文件的描述信息。
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(" - " + objectSummary.getKey() + "  " +
                    "(size = " + objectSummary.getSize() + ")");
        }

    // 关闭OSSClient。
        ossClient.shutdown();
    }

    @Override
    public void deleteFile(String fileName) {

    }
//上传文件，自己搞
    @Override
    public String uploadFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();//获取全名
        System.out.println(originalFilename);
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(fileType);
        String datePath =new DateTime().toString("yyy/MM/dd");
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String newName=fileName+fileType;
        //生成文件夹   avatar/2021/9/12/9c6496227b7b4fcaba74daae5ea4b3c8.jpg
        fileName= datePath+"/"+newName;
      return "你妈只嗨"+fileName;

    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpg";
    }


}
